const { SerialPort } = require('serialport');

const app = {
  namespaced: true,
  state: {
    port: null
  },
  mutations: {
    COM_SET(state, paylod) {
      state.port = paylod
    },
  },
  actions: {
    COM_CONNECT_ACTION({ commit }, paylod) {
      return new Promise((resolve, reject) => {
        let port = new SerialPort(paylod.config, (err) => {
          if (err) {
            console.log(err);
            port = null;
            commit('COM_SET', null);
            reject(err);
          } else {
            commit('COM_SET', port);
            resolve();
          }
        });
  
        // 当串口打开时触发
        port.on('open', paylod.open);
        // 监听串口数据
        port.on('data', paylod.data);
      })
    },
    COM_CLOSE_ACTION({ commit, rootState }, paylod) {
      console.log('com连接关闭');
      return new Promise((resolve, reject) => {
        if (rootState.com.port) {
          rootState.com.port.close((err) => {
            if (err) {
              console.error('Failed to close serial port:', err);
            } else {
              console.log('Serial port is closed');
            }
            commit('COM_SET', null);
            resolve();
          });
        } else {
          commit('COM_SET', null);
          resolve();
        }
      })
    },
  }
}

export default app
